<script setup>
import { ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import {
  getUnitList,
  getUserDetail,
  getUserList,
  userUpdateBatch,
} from '@/api/manager/systemManage/user.js'
import { tenantPageList } from '@/api/manager/dataManage/tenant.js'
import { relatedPageList } from '@/api/manager/dataManage/related'
import { parkPageList } from '@/api/manager/dataManage/park'
import { useTableList } from '@/hooks/useTableList'
import { useDict } from '@/hooks/useDict'

const { dict, getDictValue } = useDict([
  'inspection_inspection_type',
  'inspector_post_type',
  'yn',
])

const dialogVisible = ref(false)
const searchParams = ref({
  type: ['1', '2', '3'],
  isPatrol: 0,
})

const {
  Search,
  toggleSearchStatus,
  showToggle,
  handleToggleSearch,
  tableData,
  paginationParams,
  total,
  addRef,
  currentDetail,
  initTableList,
  handleSizeChange,
  handleReset,
  handleDelete,
  handleAdd,
  handleEdit,
  searchFromRef,
} = useTableList(searchParams, getUserList)

const props = defineProps({
  detail: {
    type: Object,
  },
})
watch(
  () => props.detail,
  () => {
    if (props.detail.pkid) {
      handleDetail()
    } else {
      form.value.areaId = props.detail.areaId || ''
    }
  },
)
const emit = defineEmits(['close'])
const title = ref('')
const handleClose = (isFlash) => {
  form.value = { enabled: '1' }
  formRef.value.clearValidate()
  multipleSelection.value = []
  tableData.value = []
  dialogVisible.value = false
  searchParams.value = {
    type: ['1', '2', '3'],
    isPatrol: 0,
  }
  emit('close', isFlash)
}
const formRef = ref()
const form = ref({
  enabled: '1',
})
const rules = ref({
  checkType: [{ required: true, message: '请选择检查类型', trigger: 'blur' }],
  patrolPost: [{ required: true, message: '请选择岗位类型', trigger: 'blur' }],
  areaId: [{ required: true, message: '请选择所属园区', trigger: 'blur' }],
  enabled: [{ required: true, message: '请选择是否启用', trigger: 'blur' }],
})

const multipleSelection = ref([])
const handleSelectionChange = (val) => {
  multipleSelection.value = val
}
const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid, fields) => {
    if (valid) {
      if (multipleSelection.value.length === 0 && !form.value.pkid) {
        ElMessage.warning('请选择检查人员')
        return
      }
      let params = {}
      // const coreUserMetaInfo = JSON.parse(JSON.stringify(form.value))
      if (!form.value.pkid) {
        const userIds = multipleSelection.value.map((i) => {
          return i.pkid
        })
        params.userIds = userIds
      } else {
        params.userIds = [form.value.pkid]
      }
      params.coreUserMetaInfo = {
        areaId: form.value.areaId,
        isPatrol: 1,
        patrolPost: form.value.patrolPost,
        checkType:
          form.value.checkType.length > 0 ? form.value.checkType.join(',') : '',
      }
      try {
        let res = await userUpdateBatch(params)
        if (res.success) {
          ElMessage.success('保存成功')
          handleClose(true)
        } else {
          ElMessage.error(res.message)
        }
      } catch (error) {
        console.log('error', error)
      }
    } else {
      ElMessage.warning('请正确录入信息')
    }
  })
}
const handleDetail = async () => {
  const res = await getUserDetail({ pkid: props.detail.pkid })
  if (res.success) {
    form.value = {
      pkid: res.data.userInfo.pkid,
      patrolPost: res.data.coreUserMetaInfo.patrolPost,
      checkType: res.data.coreUserMetaInfo.checkType
        ? res.data.coreUserMetaInfo.checkType.split(',')
        : [],
      areaId: res.data.coreUserMetaInfo.areaId,
    }
    handleChangeAreaId(res.data.coreUserMetaInfo.areaId, false)
  } else {
    ElMessage.error(res.message)
  }
}

const typeOptions = ref([
  {
    label: 'OA',
    value: '1',
  },
  {
    label: '承租方',
    value: '2',
  },
  {
    label: '相关方',
    value: '3',
  },
])

const parkOptions = ref([])
const initParkOptions = async () => {
  const res = await parkPageList({
    pageIndex: 1,
    pageSize: 9999,
    enable: '1',
    hasHidden: 1,
  })
  parkOptions.value = res.data.list
  if (props.detail.areaId) {
    handleChangeAreaId(props.detail.areaId, false)
  }
}

const relatedOptions = ref([])
const initRelatedOptions = async () => {
  const res = await relatedPageList({ pageIndex: 1, pageSize: 9999 })
  relatedOptions.value = res.data.list
}

const postOptions = ref([])
const handleChangeAreaId = (val, isReset = true) => {
  const currentObj = parkOptions.value.find((i) => i.pkid === val)
  if (!currentObj) {
    return
  }
  if (currentObj.name === '四联投资') {
    postOptions.value = dict.value['inspector_post_type'].filter((i) =>
      ['主要负责人', '分管安全负责人', '安督办'].includes(i.name),
    )
  } else if (currentObj.name === '资产分公司') {
    postOptions.value = dict.value['inspector_post_type'].filter((i) =>
      [
        '主要负责人',
        '分管安全负责人',
        '安监部',
        '综合管理部',
        '园区管理部',
        '资产管理部',
      ].includes(i.name),
    )
  } else {
    postOptions.value = dict.value['inspector_post_type'].filter((i) =>
      ['负责人', '管理人员', '值守人员'].includes(i.name),
    )
  }

  if (isReset) {
    form.value.patrolPost = ''
  }
}
const defaultProps = ref({
  label: 'name',
  value: 'pkid',
})
const unitOptions = ref([])
const initUnitOptions = async () => {
  const res = await getUnitList()
  if (!res.success) {
    ElMessage.error(res.message)
    return
  }
  unitOptions.value = res.data
}
const tenantOptions = ref([])
const initTenantOptions = async () => {
  const res = await tenantPageList({ pageIndex: 1, pageSize: 9999 })
  tenantOptions.value = res.data.list
}
const relatedUnitContent = ref('')
const tenantUnitContent = ref('')
const searchType = ref('')
const handleChangeType = () => {
  searchParams.value.unitId = ''
  searchParams.value.unitContent = ''
  if (searchType.value) {
    searchParams.value.type = [searchType.value]
  } else {
    searchParams.value.type = ['1', '2', '3']
  }
  relatedUnitContent.value = ''
  tenantUnitContent.value = ''
}
const handleResetCustom = () => {
  searchType.value = ''
  relatedUnitContent.value = ''
  tenantUnitContent.value = ''
  const params = {
    type: ['1', '2', '3'],
    isPatrol: 0,
  }
  handleReset(params)
}
const handleSearch = () => {
  searchParams.value.unitContent =
    relatedUnitContent.value || tenantUnitContent.value
  initTableList(1)
}
watch(
  () => dialogVisible.value,
  (newVal) => {
    if (newVal) {
      initTableList(1)
      initParkOptions()
      initRelatedOptions()
      initUnitOptions()
      initTenantOptions()
    }
  },
)
defineExpose({ dialogVisible, title })
</script>

<template>
  <v-modal
    class="custom-modal"
    v-model:visible="dialogVisible"
    :title="title"
    width="1100px"
    @ok="handleSubmit"
    @close="handleClose(false)"
  >
    <div class="form-wrapper">
      <el-form
        ref="formRef"
        class="form"
        :model="form"
        :rules="rules"
        label-width="100"
      >
        <el-form-item label="所属园区" prop="areaId">
          <el-select
            v-model="form.areaId"
            placeholder="请选择"
            style="width: 200px"
            @change="handleChangeAreaId"
          >
            <el-option
              v-for="item in parkOptions"
              :key="item.pkid"
              :label="item.name"
              :value="item.pkid"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="检查类型" prop="checkType">
          <el-checkbox-group v-model="form.checkType">
            <el-checkbox
              :label="item.value"
              v-for="item in dict['inspection_inspection_type']"
              :key="item"
              >{{ item.name }}</el-checkbox
            >
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="岗位类型" prop="patrolPost">
          <el-radio-group v-model="form.patrolPost">
            <el-radio
              :value="item.value"
              v-for="item in postOptions"
              :key="item"
              >{{ item.name }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <!-- <el-form-item label="是否启用" prop="enabled">
          <el-radio-group v-model="form.enabled">
            <el-radio
              v-for="(item, index) of dict['yn']"
              :key="index"
              :label="item.value"
              >{{ item.name }}</el-radio
            >
          </el-radio-group>
        </el-form-item> -->
      </el-form>
      <div class="body" v-if="!form.pkid">
        <div class="custom-table-list-wrapper">
          <div class="search" :class="{ active: toggleSearchStatus }">
            <div class="search-left" ref="searchFromRef">
              <el-form class="search-form" inline>
                <el-form-item label="类型">
                  <el-select
                    class="search-select"
                    v-model="searchType"
                    placeholder="请选择"
                    clearable
                    @change="handleChangeType"
                  >
                    <el-option
                      v-for="(item, index) of typeOptions"
                      :key="index"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item label="OA单位" v-if="searchType === '1'">
                  <!-- <el-select
                    class="search-select"
                    v-model="searchParams.unitId"
                    placeholder="请选择"
                    clearable
                  >
                    <el-option
                      v-for="(item, index) of unitOptions"
                      :key="index"
                      :label="item.name"
                      :value="item.pkid"
                    />
                  </el-select> -->
                  <!-- <el-cascader
                    class="search-select"
                    v-model="searchParams.unitId"
                    :options="unitOptions"
                    check-strictly
                    :render-after-expand="false"
                    :props="defaultProps"
                    clearable
                  /> -->
                  <el-tree-select
                    class="search-select"
                    v-model="searchParams.unitId"
                    :data="unitOptions"
                    check-strictly
                    :render-after-expand="false"
                    :props="defaultProps"
                    clearable
                  />
                </el-form-item>
                <el-form-item label="承租方单位" v-if="searchType === '2'">
                  <el-select
                    class="search-select"
                    v-model="tenantUnitContent"
                    placeholder="请选择"
                    clearable
                    filterable
                    allow-create
                  >
                    <el-option
                      v-for="(item, index) of tenantOptions"
                      :key="index"
                      :label="item.name"
                      :value="item.pkid"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item label="相关方单位" v-if="searchType === '3'">
                  <el-select
                    class="search-select"
                    v-model="relatedUnitContent"
                    placeholder="请选择"
                    clearable
                    filterable
                    allow-creates
                  >
                    <el-option
                      v-for="(item, index) of relatedOptions"
                      :key="index"
                      :label="item.name"
                      :value="item.pkid"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item label="关键词">
                  <el-input
                    class="search-input"
                    v-model="searchParams.keywords"
                    placeholder="请输入真实姓名"
                    :suffix-icon="Search"
                    clearable
                  ></el-input>
                </el-form-item>
              </el-form>
              <a class="search-left-toggle" @click="handleToggleSearch">
                <svg-icon :name="toggleSearchStatus ? 'up' : 'down'" />
                {{ toggleSearchStatus ? '收起' : '展开' }}
              </a>
            </div>
            <div class="search-right">
              <el-button type="primary" @click="handleSearch"
                ><svg-icon name="search" size="14px" />搜索</el-button
              >
              <el-button @click="handleResetCustom"
                ><svg-icon name="reset" size="17px" />重置</el-button
              >
            </div>
          </div>
          <div class="content">
            <div class="content-table">
              <el-table
                class="custom-table"
                :data="tableData"
                @selection-change="handleSelectionChange"
              >
                <el-table-column type="selection" width="60px" />
                <el-table-column type="index" label="序号" width="60px" />
                <el-table-column prop="userName" label="真实姓名" width="120" />
                <el-table-column
                  prop="userPhone"
                  label="联系方式"
                  width="120"
                />
                <el-table-column prop="userPhone" label="分类" width="80">
                  <template #default="scope">
                    {{ getDictValue('user_type', scope.row.type) }}
                  </template>
                </el-table-column>
                <el-table-column prop="deptName" label="单位">
                  <template #default="scope">
                    {{
                      scope.row.unitName ||
                      scope.row.relationUnit ||
                      scope.row.unitContent ||
                      scope.row.oaunit
                    }}
                  </template>
                </el-table-column>
                <el-table-column prop="deptName" label="部门" />
                <!-- <el-table-column prop="roleName" label="角色" /> -->
              </el-table>
            </div>
            <div class="content-page">
              <el-pagination
                class="custom-pagination"
                :current-page="paginationParams.pageIndex"
                :page-size="paginationParams.pageSize"
                background
                :page-sizes="[10, 20, 30, 50]"
                layout="total, prev, pager, next, sizes, jumper"
                :total="total"
                @size-change="handleSizeChange"
                @current-change="initTableList"
              />
            </div>
          </div>
        </div>
      </div>
    </div>
  </v-modal>
</template>

<style lang="scss" scoped>
@import '@/assets/styles/table.scss';

.form-wrapper {
  padding: 20px;
}

.content {
  padding: 0;
}

.body {
  border-top: 1px solid #d5deed;
  padding-top: 20px;
}

.search {
  box-shadow: none;
  // border-radius: 0;
  padding: 0;
  height: 40px;
  // margin-bottom: 0;
}
</style>
